package jpa;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Stateful;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 * Session Bean implementation class StatefulBean
 */
@Stateful
@EJB(name="StatefulBean", beanInterface=IStatefulBean.class)
public class StatefulBean implements IStatefulBean
{
	

	@PersistenceContext
	EntityManager em;
	
	private boolean loggedIn;
	private Member m_mem;
	private Cache m_cache;
    
    
    public StatefulBean() 
    { 	
    	loggedIn = false;    
    	
    }


	/*@Override
	public Member getMember() 
	{
		Member m;
		// Query q = em.createQuery("SELECT m FROM Member m WHERE m.memId = '" + 1 + "'");
		m = (Member) q.getSingleResult();
		return m;
	}*/


	@Override
	public void login(String user, String password)
	{
		Member m;
		Query q = em.createQuery("SELECT m FROM Member m WHERE m.memName = '" + user + "'");	
		m = (Member)q.getSingleResult();			
		
		if(!q.equals(null))
		{
			m = (Member)q.getSingleResult();
			
			if(m.getMemPass().equals(password))
			{			
					loggedIn = true;
					m_mem = m;			
			}
			else
			{
				loggedIn = false;
			}
		}
		else
		{
			loggedIn = false;
		}
	
	}
	
	@Override
	public int getAdminStatus()
	{
		return m_mem.getMemAdmin();
	}
	@Override
	public void logoff()
	{
		loggedIn = false;
		m_mem = null;
	}
	
	@Override
	public boolean getLoggedIn()
	{
		return loggedIn;
	}
	
	@Override
	public Member getLoggedInMember()
	{
		return m_mem;
	}
	public List<Cache> getMemberCaches()
	{
		System.out.println("In getMemberCaches()");
		
		Query q = em.createQuery("SELECT c FROM Cache c");	
		List<Cache> caches = q.getResultList();
		
		System.out.println("Got all caches");
		
		List<Cache> ret = new ArrayList<Cache>();
		for(int i = 0; i < caches.size(); i++)
		{
			if(caches.get(i).getMember().getMemId() == m_mem.getMemId())
			{
				System.out.println(caches.get(i).getCacheName());
				ret.add(caches.get(i));
			}
		}
    	return ret;
	}


	@Override
	public void setCache(Cache c)
	{
		m_cache = c;
	}


	@Override
	public Cache getCache()
	{
		return m_cache;
	}

}
